//
//  recordViewController.m
//  picRecodeDemo
//
//  Created by glendale on 13-6-21.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "recordViewController.h"
#import "AppDelegate.h"

@interface recordViewController ()

@end

@implementation recordViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(NSString*)soundfileTextPath{
    
    NSLog(@"FILENAME=====%@",[self recordName]);
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    //NSString *soundFilePath= [NSString stringWithFormat:@"/Recode/%@",self.recordName];
    NSString *soundFilePath= [NSString stringWithFormat:@"/%@",self.recordName];
    
    //打印文件路径
    NSLog(@"%@",documentPath);
    
    return [documentPath stringByAppendingPathComponent:soundFilePath];
}

-(void)prepareForRecord {
    

    self.recordName = [NSString stringWithFormat:@"card_sound_%@.caf",@"12"];
    //self.recordId = [[itemView.itemDate Card_id] integerValue];
    
    //init audioSession
    NSURL *newURL=[[NSURL alloc]initFileURLWithPath:[self soundfileTextPath]];
    self.soundFileURL=newURL;
    NSLog(@"====11==%@",self.soundFileURL);
 
    
    NSError *recordErr = nil;
    AVAudioSession *audioSession=[AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&recordErr];
    audioSession.delegate=self;
    [audioSession setActive:YES error:&recordErr];
    self.auSession = audioSession;
    
    self.recording=NO;
    self.playing=NO;
    
}

-(void)recordOrStop:(UIButton*)sender{
    
    if (self.recording) {
        [self.soundRecorder stop];
        self.recording=NO;
        self.soundRecorder=nil;

        [sender setTitle:@"录音" forState:UIControlStateNormal];
        [self.auSession setActive:NO error:nil];
        
    }else{
        
        //NSFileManager *manager=[NSFileManager defaultManager];
        //NSString *soundFilePath=[self soundfileTextPath];
        //NSURL *url=[[NSURL alloc]initFileURLWithPath:soundFilePath];
        
        NSMutableDictionary *recordSettings =[[NSMutableDictionary alloc]init];
        [recordSettings setObject:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
        [recordSettings setObject:[NSNumber numberWithFloat:11025.0] forKey:AVSampleRateKey];
        [recordSettings setObject:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
        
//        [recordSettings setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
//        [recordSettings setObject:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
//        [recordSettings setObject:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
        
        //音频质量,采样质量
        [recordSettings setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];
        
        NSError *recorderError=nil;
        AVAudioRecorder *newRecorder=[[AVAudioRecorder alloc]initWithURL:self.soundFileURL settings:recordSettings error:&recorderError];
       
        
        if (recorderError) {
            UIAlertView *ALTER=[[UIAlertView alloc]initWithTitle:@"Can't recorder" message:[recorderError localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [ALTER show];
           
        }
        
        self.soundRecorder=newRecorder;
       
        
        self.soundRecorder.delegate=self;
        
        [self.soundRecorder prepareToRecord];
        
        [self.soundRecorder recordForDuration:(NSTimeInterval)70];
        [sender setTitle:@"停止录音" forState:UIControlStateNormal];
        self.recording=YES;
        
      
    }

    
}

-(void)playback:(NSInteger)index
{
    
//    NSFileManager *manager=[NSFileManager defaultManager];
////    NSString *soundFilePath=[self soundfileTextPath];
////    NSLog(@"pp==%@",soundFilePath);
//    
//    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//    NSString *soundFilePath= [documentPath stringByAppendingPathComponent:@"mm_switch.mp3"];
//    
//    NSLog(@"%@",soundFilePath);
////    NSURL *url=[[NSURL alloc]initFileURLWithPath:soundFilePath];
//    NSURL *url = [NSURL fileURLWithPath:soundFilePath];
//    NSLog(@"%@",url);
//    
//    if ([manager fileExistsAtPath:soundFilePath])
//    {
//        AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
//
//        self.audioPlayer = player;
//        [self.audioPlayer prepareToPlay];
//        [self.audioPlayer play];
//        NSLog(@"播放==%@",url);
//    }
//    else
//    {
//        NSLog(@"文件路径不存在");
//    }
    
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    NSString *currentIp = myDelegate.currentIp;
    NSString *urlString = [NSString stringWithFormat:@"http://%@/%@/%@/%@",currentIp,@"PadData",@"PadResourceFiles/FunctionCheckRecording",[self getNameInRecordListByIndex:index]];
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@",urlString);
    NSURL *serverUrl = [NSURL URLWithString:urlString];
    NSData *audioData = [NSData dataWithContentsOfURL:serverUrl];
    
    NSError *error = nil;
//    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:serverUrl error:&error];
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:audioData error:&error];

    if (error)
    {
        NSLog(@"error:%@",[error description]);
        return;
    }
    self.audioPlayer = player;
    self.audioPlayer.delegate = self;
    [self.audioPlayer prepareToPlay];
    [self.audioPlayer play];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSLog(@"audioPlayerDidFinishPlaying……");
    
    //当停止播放的时候，发送一个消息
    [[NSNotificationCenter defaultCenter] postNotificationName:MM_RECORD_PAUSE_MSG_ object:nil];
}

-(void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error{
    NSLog(@"录音出错");
}

//根据序号得到要播放的录音的名称
-(NSString *)getNameInRecordListByIndex:(NSInteger)index
{
    return [[[MainMenuDataModel sharedMainMenuDataModel].arrRecodeList objectAtIndex:index] objectForKey:MM_RECORD_LIST_RECORD_NAME_KEY_STR_];
}

-(void)stopBack
{
    [self.audioPlayer stop];
}

@end
